<?php

// The following functions supplement the Role class to add 
// functionality for reading and manipulating permissions.

// Function to check permissions on a role instead of a user.
function RoleHasPermission($Role, $Permission = ""){
   if (array_key_exists($Permission,$Role->Permissions)){
      return ($Role->Permissions[$Permission] == '1');
   }
}

// Function to build a list of ids for roles having a certain 
// permission.
function GetRoleIDsWithPermission($Context, $Permission){
   $RoleManager = $Context->ObjectFactory->NewContextObject($Context, 'RoleManager');
   $RoleData = $RoleManager->GetRoles();
   $RoleIDs = array();
   while ($Row = $Context->Database->GetRow($RoleData)){
      $Role = $Context->ObjectFactory->NewContextObject($Context, 'Role');
      $Role->Clear();
      $Role->GetPropertiesFromDataSet($Row);
      if (RoleHasPermission($Role,$Permission)){
         array_push($RoleIDs,$Role->RoleID);
      }
   }
   return $RoleIDs;
}

// Function to save just the permissions of a role to the database.
function SaveRolePermissions($Context,$Role){
   $Role->FormatPropertiesForDatabaseInput();
   // Build a custom query to replace the role permissions.
   $Query = $Context->ObjectFactory->NewContextObject($Context, 'SqlBuilder');
   $Query->SetMainTable('Role','r');
   $Query->AddFieldNameValue('Permissions',$Role->Permissions);
   $Query->AddWhere('r','RoleID','',$Role->RoleID,'=');
   // Update the database and report errors if necessary.
   $RowCount = $Context->Database->Update($Query,'AutoHide','RemovePermissionKey',
        $Context->GetDefinition('AutoHide_ErrorRemovingPermissions'));
   if ($RowCount != 1){
      $Context->WarningCollector->Add(
        $Context->GetDefinition('AutoHide_ErrorRemovingPermissions'));
   }
}

// Function to remove a permission key from a role in the database.
function RemovePermissionKeyFromRole($Role, $Permission = ""){
   if (array_key_exists($Permission,$Role->Permissions)){
      unset($Role->Permissions[$Permission]);
   }
}

?>
